package com.ktjy.t382.ch01.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ktjy.t382.ch01.entity.vo.R;
import com.ktjy.t382.ch01.util.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

@WebFilter(urlPatterns = "/user/*", filterName = "myFilter")
public class MyFilter implements Filter {
    @Resource
    ObjectMapper objectMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        servletResponse.setContentType("text/plain;charset=UTF-8");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        if ("/ch01/user/login".equals(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = request.getHeader("token");
        RedisUtil redisUtil = new RedisUtil();
        String token1 = redisUtil.getKey("token");
        if (token.equals(token1)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            System.out.println("财富会低语，肚子会变大");
            servletResponse.getWriter().println(objectMapper.writeValueAsString(R.fail("哦我的小天使"+token+"，财富会低语，肚子会变大")));
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
